package com.gaohe.controller;

import cn.hutool.crypto.digest.MD5;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gaohe.common.BaseContext;
import com.gaohe.common.R;
import com.gaohe.common.S;
import com.gaohe.pojo.Admin;
import com.gaohe.service.AdminService;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.concurrent.TimeUnit;

@Slf4j
@RestController
@RequestMapping("/admin")
public class AdminController {

    @Autowired
    private AdminService adminService;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 登录
     *
     * @param loginAdmin
     * @return
     */
    @PostMapping("/login")
    public R login(@RequestBody Admin loginAdmin) {
        //获取用户名 密码
        String username = loginAdmin.getUsername();
        String password = loginAdmin.getPassword();
        //根据用户名查询
        LambdaQueryWrapper<Admin> qw = new LambdaQueryWrapper<>();
        qw.eq(ObjectUtils.isNotEmpty(username), Admin::getUsername, username);
        Admin admin = adminService.getOne(qw);
        //密码加密
        password = MD5.create().digestHex(password);
        if (ObjectUtils.isEmpty(admin)) {
            return R.error(S.USERNAME_ERROR);
        }

        if (!admin.getPassword().equals(password)) {
            return R.error(S.PASSWORD_ERROR);
        }
        if (admin.getStatus() != S.STATUS_OPEN) {
            return R.error(S.STATUS_ERROR);
        }
        //存 redis
        //session.setAttribute(S.SESSION_KEY, admin.getId());
        redisTemplate.opsForValue().set(
                "auth" + admin.getId(),
                admin.getId(),
                30,TimeUnit.MINUTES);
       //BaseContext.setCurrentId(admin.getId());
        //返回
        return R.success(admin.getId());
    }

    /**
     * 登出
     *
     * @return
     */
    @GetMapping("/logout")
    public R logout() {
        Long id = BaseContext.getCurrentId();
        redisTemplate.delete("auth"+id);
        return R.success(S.LOGOUT_SUCCESS);
    }

    /**
     * 分页查询
     *
     * @param page     页码
     * @param pageSize 大小
     * @param name     姓名
     * @return 分页结果
     */
    @GetMapping("/page")
    public R page(
            @RequestParam Integer page,
            @RequestParam Integer pageSize,
            @RequestParam(required = false) String name) {
        log.info("分页查询，页码：{}，展示条目数：{}，模糊查询姓名：{}", page, pageSize, name);
        Page<Admin> adminPage = new Page<>(page, pageSize);
        LambdaQueryWrapper<Admin> qw = new LambdaQueryWrapper<>();
        qw.like(ObjectUtils.isNotEmpty(name), Admin::getName, name);
        qw.orderByDesc(Admin::getUpdateTime);
        qw.orderByAsc(Admin::getName);
        adminService.page(adminPage, qw);
        return R.success(adminPage);
    }

    /**
     * 新增
     *
     * @param admin
     * @return
     */
    @PostMapping
    public R insert(@RequestBody Admin admin) {
        log.info("admin:{}", admin);
        String password = MD5.create().digestHex(S.DEFAULT_PASSWORD);
        admin.setPassword(password);
        admin.setStatus(S.STATUS_OPEN);
        adminService.save(admin);
        return R.success(S.INSERT_SUCCESS);
    }

    /**
     * 根据id查询
     *
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<Admin> getByID(@PathVariable("id") Long id) {
        Admin admin = adminService.getById(id);
        return R.success(admin);
    }

    /**
     * 修改状态
     *
     * @param admin
     * @return
     */
    @PutMapping("/changeStatus")
    public R<String> changeStatus(@RequestBody Admin admin) {
        log.info("修改信息admin：{}", admin);
        boolean update = adminService.updateById(admin);
        return update ? R.success(S.UPDATE_SUCCESS) : R.error(S.UPDATE_ERROR);
    }

    /**
     * 修改
     *
     * @param admin
     * @return
     */
    @PutMapping
    public R update(@RequestBody Admin admin) {
        Admin admin1 = adminService.getById(admin.getId());
        if (!admin.getPassword().equals(admin1.getPassword())) {
            admin.setPassword(MD5.create().digestHex(admin.getPassword()));
        }
        boolean update = adminService.updateById(admin);
        return update ? R.success(S.UPDATE_SUCCESS) : R.error(S.UPDATE_ERROR);

    }

    /**
     * 用户端 查看管理员的 -姓名 -手机号
     *
     * @return
     */
    @GetMapping
    public R getAll() {
        return R.success(adminService.list());
    }
}
